#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>

char* host_name="127.0.0.1";//"192.168.100.1";
int port=7777;

int main(int argc, char* argv[])
{
	char buf[4096];
	char message[1024];
	int socket_descriptor;

	char* message_str="hello, network";

	if(argc < 2)
	{
		printf("send default string.\n");
	}
	else
	{
		message_str=argv[1];
	}

	//创建socket
	if((socket_descriptor=socket(AF_INET, SOCK_STREAM, 0))==-1)
	{
		perror("error opening socket\n");
		exit(1);
	}

	//处理对方IP数据

	struct hostent * server_host_name;
	if((server_host_name=gethostbyname(host_name))==0)
	{
		herror("can not resoving localhost\n");
		exit(1);
	}

	struct sockaddr_in pin;
	bzero(&pin, sizeof(pin));
	pin.sin_family=AF_INET;
	pin.sin_addr.s_addr=((struct in_addr*)(server_host_name->h_addr))->s_addr;//对方IP
	pin.sin_port=htons(port);

	//建立连接
	if(connect(socket_descriptor, (void*)&pin, sizeof(pin))==-1)
	{
		perror("can not connecting to server\n");
		exit(1);
	}

	//发送数据
	if(send(socket_descriptor, message_str, strlen(message_str), 0)==-1)
	{
		perror("can not send message\n");
		exit(1);
	}

	//接收
	if(recv(socket_descriptor, buf, sizeof(buf), 0)==-1)
	{
		perror("can not receive response\n");
		exit(1);
	}

	//关闭
	close(socket_descriptor);
	return 0;
}
